<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class UserCommon extends REST_Controller {

    protected $rules = array(
        "login" => array(
            array(
                'field'   => 'account', 
                'label'   => '账号', 
                'rules'   => 'trim|required|min_length[6]|max_length[20]|callback_account_check'
            ),
            array(
                'field'   => 'passwd', 
                'label'   => '密码', 
                'rules'   => 'trim|required|min_length[6]|max_length[20]|regex_match[/^[a-zA-Z0-9]*$/]|callback_pwd_check'
            )
        ),
        "sendCode" => array(
            array(
                'field'   => 'mobile',
                'label'   => '手机号码',
                'rules'   => 'trim|required|is_mobile'
                )
        ),
        "resign" => array(
            array(
                'field'   => 'mobile', 
                'label'   => '昵称', 
                'rules'   => 'trim|required|is_mobile|callback_account_exist'
            ),
            array(
                'field'   => 'passwd', 
                'label'   => '密码', 
                'rules'   => 'trim|required|min_length[6]|regex_match[/^[a-zA-Z][a-zA-Z0-9]+$/]'
            ),
            array(
                'field'   => 'code', 
                'label'   => '验证码', 
                'rules'   => 'trim|required|callback_captcha_verify'
            ),
            array(
                'field'   => 'reg_invite_mobile', 
                'label'   => '邀请人手机号', 
                'rules'   => 'trim|is_mobile|callback_reg_mobile_check'
            ),array(
                'field'   => 'reg_invite_code', 
                'label'   => '邀请码', 
                'rules'   => 'trim'
            )
        ),
        "getpwd" => array(
            array(
                'field' => 'mobile',
                'label' => '电话',
                'rules' => 'trim|required|is_mobile'
            )
        ),
        "setpwd" => array(
            array(
                'field'   => 'mobile', 
                'label'   => '电话', 
                'rules'   => 'trim|required|is_mobile'
            ),
            array(
                'field'   => 'code', 
                'label'   => '验证码', 
                'rules'   => 'trim|required'
            ),
            array(
                'field'   => 'passwd', 
                'label'   => '密码', 
                'rules'   => 'trim|required|min_length[6]|matches[repasswd]|regex_match[/^[a-zA-Z][a-zA-Z0-9]+$/]'
            ),
            array(
                'field'   => 'repasswd', 
                'label'   => '验证密码', 
                'rules'   => 'trim|required|min_length[6]'
            )
        )
    );

    private $rdata = array();

    function __construct(){  
        
        parent::__construct();
        $this->load->model('account_model', 'macc', 'default');
        $this->returnInfo = lang('returnInfo');
        $this->rdata['returnNo'] = '0000';
        $this->rdata['returnInfo'] = $this->returnInfo['0000'];
        $this->rdata['returnTime'] = time();
        $this->rdata['returnData'] = (object)array();
    }

    public function index() {   
        
    }

    // 登录login
    public function login_post() {

        $this->form_validation->set_rules($this->rules['login']);
        if ($this->form_validation->run() == FALSE) {
            // 返回失败
            $this->rdata['returnNo']   = '0011';
            $this->rdata['returnInfo'] = validation_errors();

        } else {

            if ($this->info['is_check']) {

                $this->info['nickname'] = $this->info['realname'];
            }

            if ($this->IS_APP) {
                $token = array('id' => $this->info['id'], 'logintime' => time());
                $this->info['token'] = $this->aes->encrypt(json_encode($token));
                $this->cache->save('Cache:BOCAUTH:'.$this->info['id'], $this->info['token'],3600);
            }
            
            $info = $this->info;
            
            // set session
            $array = array(
                'UAID'   => $this->info['id']
            );

            $this->session->set_userdata( $array );
            $pre = $this->_getCacheKey('message_get',$this->info['id']);
            $readed_id = $this->cache->get($pre);
            $readed_count = is_array($readed_id)?count($readed_id):0;
            $where = array("in"=>array("toer",array(0,$this->info['id'])));
            $this->load->model("msgs_model","msgs");
            $msgs_count = $this->msgs->get_count_all($where);
            $unread_count = $msgs_count - $readed_count;
            $this->info['unread_count'] = $unread_count;
            $this->info['is_bind_card'] = 0;
            if ($this->info['bid']) {

                $this->info['is_bind_card'] = 1;
            }
            
            if($this->info['is_check']){

                $this->info['nickname'] = $this->info['realname'];
                $this->info['chinaid'] = substr_replace($this->info['chinaid'], '***********', 4,-4);
            }

            unset($this->info['passwd']);
            unset($this->info['chinaid_check']);
            unset($this->info['id']);
            unset($this->info['bid']);
            unset($this->info['money']);
            unset($this->info['other_account']);
            unset($this->info['bank_code']);
            unset($this->info['bank_card']);
            unset($this->info['bank_name']);
            unset($this->info['bank_phone']);
            unset($this->info['province_id']);
            unset($this->info['city_id']);
            $this->rdata['returnData'] = $this->info;
        }

        
        $this->response($this->rdata);
    }

    // 登录login
    public function resign_post() {

        $this->form_validation->set_rules($this->rules['resign']);
        $data = $this->post();

        if ($this->form_validation->run() == FALSE) {

            $errs = form_errors();
            $errs_str = '';
            foreach($errs as $key => $value){
                $errs_str .= ' '.$value;
            }
            $this->rdata['returnInfo'] = $errs_str;
            $this->rdata['returnNo'] = '0011';
            $this->response($this->rdata);
        }
        if (isset($data['reg_invite_mobile'])) {
            if ($data['mobile'] == $data['reg_invite_mobile']) {
                $this->rdata['returnInfo'] = '推荐人手机不能是自己';
                $this->rdata['returnNo'] = '0011';
                $this->response($this->rdata);
            }
        }
        

        $mobile = $data['mobile'];
        $passwd = $data['passwd'];

        //检测账号是否已注册
        $this->load->model('account_model','maccount');
        $where = array('mobile'=>$mobile);
        $rs_count = $this->maccount->get_count_all($where);

        if ($rs_count>0){

            $this->rdata['returnNo'] = '0012';
            $this->rdata['returnInfo'] = '手机号已被注册！';
            $this->response($this->rdata);
        }

        $insert_data = array();
        $insert_data['account'] = $mobile;
        $insert_data['mobile'] = $mobile;
        $insert_data['nickname'] = substr_replace($mobile, '********', 2,8);
        $insert_data['passwd'] = passwd($passwd);
        $insert_data['create_at'] = date("Y-m-d H:i:s");
        if (isset($data['reg_invite_mobile'])) {
            $insert_data['reg_invite_mobile'] = $data['reg_invite_mobile'];
        }
        if (isset($data['reg_invite_code'])) {
            $insert_data['reg_invite_code'] = $data['reg_invite_code'];
        }
        
        $result = $this->maccount->create($insert_data);
        
        if($result){
            
            $this->rdata['returnNo']   = '0000';
            $this->rdata['returnInfo'] = '注册成功！';
            $content = $this->maccount->get_one($result);
            //发注册红包
            $this->send_red_package($content['id'],1);
            
            $info                  = array();
            $info['account']       = $content['account'];
            $info['mobile']        = $content['mobile'];
            $info['realname']      = $content['realname'];
            $info['nickname']      = $content['nickname'];
            $info['chinaid_check'] = $content['chinaid_check'];
            $info['thumb']         = $content['thumb']?$content['thumb']:'DEFAULT_IMG';
            $info['token']         = $content['token'];
            $info['realname']      = $content['realname'];

            $this->rdata['returnData'] = $info;
            $this->response($this->rdata);
        }
        else{
            
            $this->rdata['returnNo']   = '0050';
            $this->rdata['returnInfo'] = '数据库操作失败!';
            $this->response($this->rdata);
        }
    }


    //手机验证码 获取
    public function sendCode_post(){

        //验证规则
        $this->form_validation->set_rules($this->rules['sendCode']);
       
        $data = $this->post();
        if ($this->form_validation->run() == FALSE) {

            $errs = form_errors();
            $errs_str = '';
            foreach($errs as $key => $value){
                $errs_str .= ' '.$value;
            }
            $this->rdata['returnInfo'] = $errs_str;
            $this->rdata['returnNo']   = '0011';
            $this->response($this->rdata);
        }

        $mobile = $data['mobile'];

        $this->load->model('account_model','maccount');
        $where = array('mobile'=>$data['mobile']);
        $rs_count = $this->maccount->get_count_all($where);

        if ($rs_count > 0){

            $this->rdata['returnNo']   = '0012';
            $this->rdata['returnInfo'] = '手机号已被注册！';
            $this->response($this->rdata);
        }

        $pre = $this->_getCacheKey("sendCode_post",$data['mobile']);
        if ($next_time = $this->cache->get($pre)) {

            $this->rdata['returnInfo'] = '请勿重复点击,'.($next_time - time()+60).'s后重新发送';
            $this->rdata['returnNo']   = '0011';
            $this->response($this->rdata);
        }else{

            $this->cache->save($pre,time(),60);
        }

        $mobile = $data['mobile'];
        //发送短信 写入redis
        $result = $this->sendCodeMail($mobile);

        if (!$result) {

            $this->rdata['returnNo']   = '9999';
            $this->rdata['returnInfo'] = '验证码发送失败,请联系管理员！';
            $this->response($this->rdata);
        }

        $this->rdata['returnInfo'] = '验证码发送成功';
        $this->rdata['returnNo']   = '0000';
        $this->response($this->rdata);
    }

    //手机验证码 获取
    public function sendCodeBank_post(){

        //验证规则
        $this->form_validation->set_rules($this->rules['sendCode']);
       
        $data = $this->post();
        if ($this->form_validation->run() == FALSE) {

            $errs = form_errors();
            $errs_str = '';
            foreach($errs as $key => $value){
                $errs_str .= ' '.$value;
            }
            $this->rdata['returnInfo'] = $errs_str;
            $this->rdata['returnNo']   = '0011';
            $this->response($this->rdata);
        }

        $mobile = $data['mobile'];

        $this->load->model('account_model','maccount');

        $pre = $this->_getCacheKey("sendCode_post",$data['mobile']);
        if ($next_time = $this->cache->get($pre)) {

            $this->rdata['returnInfo'] = '请勿重复点击,'.($next_time - time()+60).'s后重新发送';
            $this->rdata['returnNo']   = '0011';
            $this->response($this->rdata);
        }else{

            $this->cache->save($pre,time(),60);
        }

        $mobile = $data['mobile'];
        //发送短信 写入redis
        $result = $this->sendCodeMail($mobile);

        if (!$result) {

            $this->rdata['returnNo']   = '9999';
            $this->rdata['returnInfo'] = '验证码发送失败,请联系管理员！';
            $this->response($this->rdata);
        }

        $this->rdata['returnInfo'] = '验证码发送成功';
        $this->rdata['returnNo']   = '0000';
        $this->response($this->rdata);
    }

    // 找回密码
    public function getPwd_post() {

        $this->form_validation->set_rules($this->rules['getpwd']);
        if ($this->form_validation->run() == FALSE) {

            // 返回失败
            $this->rdata['returnNo']   = '0011';
            $this->rdata['returnInfo'] = $this->returnInfo['0011'];
            $this->response($this->rdata);
        }else{
            $mobile = $this->input->post('mobile');
            $where = array('mobile'=>$mobile);
            $result = $this->macc->get_one($where,'id');

            if (empty($result)) {
                $this->rdata['returnNo']   = '0115';
                $this->rdata['returnInfo'] = $this->returnInfo['0115'];
                $this->response($this->rdata);
            }

            $this->load->library('juhe');
            $rand_str = rand_str(5,'0123456789');
            $pre = 'random_code_'.$this->post('mobile');
            if ($this->cache->get($pre)) {
                $this->rdata['returnNo'] = '0011';
                $this->rdata['returnInfo'] = '请勿重复点击';
                $this->response($this->rdata);
            }
            
            $this->cache->save($pre,$rand_str,60);
            $result = $this->juhe->sendMsm($mobile,$rand_str);
            if ($result) {
                $this->rdata['returnInfo'] = '验证码发送成功,请在1分钟内重置.';
                $this->rdata['returnNo']   = '0000';
            }
            $this->response($this->rdata);
        }
    }

    // 设置密码
    public function setPwd_post() {
        
        $code = $this->post('code');
        $passwd = $this->post('passwd');
        $repasswd = $this->post('repasswd');
        
         $this->form_validation->set_rules($this->rules['setpwd']);
        if ($this->form_validation->run() == FALSE) {

            $errs = form_errors();
            $errs_str = '';
            foreach($errs as $key => $value){
                $errs_str .= ' '.$value;
            }
            $this->rdata['returnInfo'] = $errs_str;
            $this->rdata['returnNo'] = '0011';
            $this->response($this->rdata);
        }else{

            $pre = 'random_code_'.$this->post('mobile');
            if ($code != $this->cache->get($pre)) {
                $this->rdata['returnNo']   = '0012';
                $this->rdata['returnInfo'] = $this->returnInfo['0012'];
            }
            else{
                $u_data = array("passwd"=>passwd($passwd),"modify_at"=>date('Y-m-d H:i:s'));
                $result = $this->macc->update($u_data,array("mobile"=>$this->post('mobile')));
                if (!$result) {
                    $this->rdata['returnNo']   = '0050';
                    $this->rdata['returnInfo'] = $this->returnInfo['0050'];
                }else{

                    $this->session->unset_userdata('tmp_id');
                    $this->rdata['returnNo']   = '0000';
                    $this->rdata['returnInfo'] = $this->returnInfo['0000'];
                }
            }
        }
        $this->response($this->rdata);
    }

    //手机验证码 验证
    public function captcha_verify($str='')
    {   

        if($str==''){
            $this->rdata['returnInfo'] = '请您输入手机验证码！';
            $this->response($this->rdata);
            return false;
        }else{
            $mobile = $this->post('mobile');
            $this->load->driver('cache', array('adapter' => 'redis'));
            $pre = 'random_code_'.$mobile;
            $randcode = $this->cache->get($pre);;
            if($randcode==$str){
                return true;
            }else{
                $this->form_validation->set_message('captcha_verify', '您输入的验证码错误，请您重新输入！');
                return false;
            }
        }
    }

    //生成验证码 存入redis 并发送手机验证码
    private function sendCodeMail($mobile){

        $this->load->library('juhe');
        $rand_str = rand_str(5,'0123456789');
        $this->load->driver('cache', array('adapter' => 'redis'));
        $pre = 'random_code_'.$mobile;
        $this->cache->save($pre,$rand_str,300);
        $result = $this->juhe->sendMsm($mobile,$rand_str);
        return $result;
    }



    // 验证密码是否正确
    public function pwd_check($pwd = false)
    {
        
        // 消除通过路由的请求
        if($this->router->method == 'pwd_check'){
            show_404();
        }
        // 帐号存在则过
        if (isset($this->info) and $this->info and is_array($this->info) ) {

            if ($pwd and passwd($pwd) == $this->info['passwd']) {
                return TRUE;
            }
            $this->form_validation->set_message('pwd_check', '用户名或密码错误,登录失败');
        } else {

            $this->form_validation->set_message('pwd_check', '');
        }

        
        return FALSE;

    }
    
    // 验证密码是否正确
    public function account_check($account = false)
    {

        if ( ! $this->info = $this->macc->find_account($account) ) {
            if ( ! $this->info = $this->macc->find_mobile($account)) {
                
                $this->form_validation->set_message('account_check', '用户名或密码错误,登录失败');
                return FALSE;
            }
        }

        if ($this->info['user_role']) {

            $this->form_validation->set_message('account_check', '账号角色不允许登录');
                return FALSE;
        }

        if (isset($this->info['thumb'])) {

            $this->info['thumb'] = UPLOAD_URL.$this->info['thumb'];
        }
        return TRUE;
    }

    // 验证手机号是否存在
    public function account_exist($account = false)
    {

        if ($this->macc->find_account($account) ) {
            
                
            $this->form_validation->set_message('account_exist', '手机号已注册');
            return FALSE;
        }
        return TRUE;
    }

    // 验证推荐人手机号是否存在
    public function reg_mobile_check($mobile = false)
    {

        if ($mobile) {
            
            if (!$this->macc->find_account($mobile)) {
                
                $this->form_validation->set_message('reg_mobile_check', '您填写的推荐人不存在，请重新填写');
                return FALSE;
            }    
        }
        return TRUE;
    }

    protected function _getCacheKey($method,$id){
        $pre_key = "Cache:Lock:user:$method:$id";
        return $pre_key;
    }

    // 发送注册红包
    public function send_red_package($id,$type,$trigger = 1){
        if (!$trigger) {

            return fale;
        }
        else{
            $this->load->model('red_package_model','mred');
            $this->load->model('red_package_user_model','mred_user');
            $where = array("type"=>$type);
            $result = $this->mred->get_one($where);
            $tmp['money'] =$result['money'];
            $tmp['type'] = $type;
            $tmp['require_money'] = $result['require_money'];
            $tmp['require_cycle'] = $result['require_cycle'];
            $tmp['note'] = $result['note'];
            $tmp['create_at'] = date("Y-m-d H:i:s");
            $tmp['expire_at'] = date("Y-m-d H:i:s",strtotime("+".$result['expire_days'].'days'));
            $tmp['aid'] = $id;

            // 创建返回
            if ($redP = $this->mred_user->get_one(array('aid' => $id, 'type' => $type))) {

                return $redP['id'];
            }
            return $this->mred_user->create($tmp);
        }
    }

}
